import React, { useState, useEffect, useCallback } from "react";
import sha256 from 'crypto-js/sha256'
import HeaderPanel from './components/HeaderPanel.js';
import CountDown from './components/CountDown.js'
import { TaskTables, Tables } from './components/TaskTables.js'
import { Block, Chain } from './modal/blockChain.js'
import toast from './utils/toast.js'

const blockChain = new Chain();

function App() {
  const [exchangeRate, setExchangeRate] = useState({});

  const [taskList, setTaskList] = useState([]);

  const [queue, setQueue] = useState([])

  const addTaskList = useCallback((data) => {
    data.txHash = sha256(data + data.timestamp).toString();
    setQueue([...queue, data]);
  }, [queue])

  //倒计时结束生成区块
  const downFinish = useCallback(() => {
    let outQueue = [];//退出列队
    let newQueue = [];//新列队
    for (let i = 0; i < queue.length; i++) {
      if (i < 5) {
        outQueue.push(queue[i]);
        continue;
      }
      newQueue.push(queue[i]);
    }
    let newBlock = new Block(outQueue, '');
    console.log('newBlock:', newBlock)
    //加链
    blockChain.addBlockToChain(newBlock);
    //设置列队
    setQueue([...newQueue]);
    // //设置TaskListif
    let newArr = [];
    if (outQueue.length > 0) {//如果队列中存在数据则需要删除taskList中的数据
      newArr = taskList.filter((val) => !outQueue.some((item) => {
        return val.timestamp === item.timestamp;
      }));
    } else {
      newArr = taskList;
    }
    outQueue.forEach(item => {
      item.prevHash = newBlock.prevHash;
      item.hash = newBlock.hash;
      item.record = true;
    })
    setTaskList([...newArr, ...outQueue]);
  }, [queue])

  //改变状态
  const changeTaskList = useCallback((timestamp) => {
    let newData = taskList.find(item => item.timestamp === timestamp)
    newData = { ...newData, isComplete: !newData.isComplete };
    let result = queue.some(item => {
      if (item.timestamp === timestamp) {
        return true
      }
    })
    if (!result) {
      addTaskList(newData);
    }else{
      toast.warning('当前计划正在列队噢！')
    }
  }, [queue])

  useEffect(() => {
    console.log('iniBiz')
    fetch('https://api.globus.furniture/forex').then(res => res.json(), err => {
      //网络错误、连接失败、无法解析对方数据
      console.error('request error', err);
    }).then(data => {
      setExchangeRate(data);
    })
  }, [])

  return (
    <div className='main-box'>
      <HeaderPanel exchangeRate={exchangeRate} addTaskList={addTaskList} blockChain={blockChain}></HeaderPanel>
      <CountDown downFinish={downFinish}></CountDown>
      <Tables title='QUEUE' resultTitle='合计' tableData={queue}></Tables>
      <TaskTables taskList={taskList} changeTaskList={changeTaskList}></TaskTables>
    </div>
  )
}

export default App;
